package com.edu.controller.front.diningcar;

import com.edu.entity.Diningcar;
import com.edu.entity.User;
import com.edu.service.diningcar.DiningCarService;
import com.edu.service.diningcar.DiningCarServiceImpl;
import com.edu.service.user.UserService;
import com.edu.service.user.UserServiceImpl;
import com.edu.utils.ParamFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author ZCN
 * @version 1.0
 * @date 2021/11/22 17:24
 */
@WebServlet("/front/querydiningcar")
public class QueryCarServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private DiningCarService diningCarService = new DiningCarServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            ParamFormat.format(req, resp);
            String username =(String) req.getSession().getAttribute("username");
            User user = userService.selectByUsername(username);
            // 拿到用户购物车列表
            List<Diningcar> diningcars = diningCarService.selectByUserid(user.getId());
            Integer sumprice = 0;
            String ids = "";
            for (Diningcar diningcar : diningcars) {
                sumprice += diningcar.getPrice();
                ids += diningcar.getId() + ",";
            }
            String realids = "";
            if(ids != ""){
                realids = ids.substring(0,ids.length()-1);
            }
            req.setAttribute("diningcars",diningcars);
            req.setAttribute("sumprice",sumprice);
            req.setAttribute("ids",realids);
            // 请求转发
            req.getRequestDispatcher("/front/diningCar.jsp").forward(req,resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
